import java.util.Arrays;

public class TwoSortedArraySort {

	public static void main(String[] args) {
		int[] a = { 1, 3, 5 };
		int[] b = { 2, 4, 6 };
		
		int[] c = mergeSorted(a, b);
		System.out.println("\r\n" + "合并排序数组："+c);
		Arrays.asList(c).forEach(e -> System.out.print(e + "   "));
	}

	/**
	 * 合并俩个排好序的数组
	 * 
	 * @param a
	 * @param b
	 */
	private static int[] mergeSorted(int[] a, int[] b) {
		if (a == null || b == null) {
			return null;
		}
		int[] c = new int[a.length + b.length];
		// a数组的最大值小于等于b数组的最小值
		if (a[a.length - 1] <= b[0]) {
			System.arraycopy(a, 0, c, 0, a.length);
			System.arraycopy(b, 0, c, a.length, b.length);
			return c;
		}
		// b数组的最大值小于等于a数组的最小值
		if (b[b.length - 1] <= a[0]) {
			System.arraycopy(b, 0, c, 0, b.length);
			System.arraycopy(a, 0, c, b.length, a.length);
			return c;
		}
		// 合并两个数组
		System.arraycopy(a, 0, c, 0, a.length);
		System.arraycopy(b, 0, c, a.length, b.length);

		//插入排序
		for (int i = 0; i < c.length; i++) {
			for (int j = 0; j < i; j++) {
				if (c[i] < c[j]) {
					int temp = c[i];
					System.arraycopy(c, j, c, j + 1, i - j);
					c[j] = temp;
				}
			}
		}

		return c;
	}

}
